package com.resou.reader.signin.style1;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.resou.reader.R;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.data.signin.model.SignIn;
import com.resou.reader.data.signin.model.SignInInfo;
import com.resou.reader.mine.paycenter.PayCenterActivity;
import com.resou.reader.signin.SignInDialog;
import com.resou.reader.signin.SignInView;
import com.resou.reader.signin.SupplementDialog;
import com.resou.reader.signin.WeekAdapter;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.WXUtils;
import com.resou.reader.utils.log.LogUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeoutException;

import butterknife.BindView;
import butterknife.OnClick;

public class SignInActivity extends ResouBaseActivity<SignInPresenter> implements SignInView,
        WeekAdapter.OnSignInInteractionListener, SupplementDialog.OnSupplementDialogInteractionListener, SignInRuleAdapter.OnTaskInteractionListener {
    private static final String TAG = "SignInActivity-APP";
    public static final String SIGN_STATUS = "sign_status";

    public static final String WEEK_DAY = "week_day";
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_continuous_check_in)
    TextView tvContinuousCheckIn;
    @BindView(R.id.week_recycler_view)
    RecyclerView weekRecyclerView;

    @BindView(R.id.cardView)
    CardView cardView;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    //    @BindView(R.id.view_pager)
//    ViewPager viewPager;
    @BindView(R.id.view_pager_card)
    CardView viewPagerCard;
    @BindView(R.id.progress_bar)
    LinearLayout progressBar;
    //    @BindView(R.id.tv_sign_in_task)
//    TextView tvSignInTask;
//    @BindView(R.id.tv_daily_task)
//    TextView tvDailyTask;
//    @BindView(R.id.tv_binding_task)
//    TextView tvBindingTask;
    @BindView(R.id.net_error_container)
    ConstraintLayout netErrorContainer;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private WeekAdapter mWeekAdapter;
    //    private TaskFragmentAdapter mFragmentAdapter;
    //    private SignInTaskFragment mSignInTaskFragment;
//    private BindingTaskFragment mTaskFragment;
//    private DailyTaskFragment mDailyTaskFragment;
    private SupplementDialog mShareDialog;
    private SupplementDialog mRechargeDialog;

//    public static Intent getStartIntent(Context context, int signStatus) {
//        Intent intent = new Intent(context, SignInActivity.class);
//        intent.putExtra(SIGN_STATUS, signStatus);
//        return intent;
//    }


    @Override
    protected void initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            getWindow().setStatusBarColor(getColor(R.color.white));
        }  //            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        //                getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        //            }
    }

    @Override
    protected void initPresenter() {
        mPresenter = new SignInPresenter(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_signin;
    }

    @Override
    protected void initView() {
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        recyclerView.setFocusable(false);
        //这一周签到列表
        mWeekAdapter = new WeekAdapter(this);
        mWeekAdapter.setInteractionListener(this);
        weekRecyclerView.setAdapter(mWeekAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        weekRecyclerView.setLayoutManager(layoutManager);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");//设置日期格式
        String date = df.format(new Date());
        tvTime.setText(date);
        // new Date()为获取当前系统时间

//        //横向滑动任务列表
//        mFragmentAdapter = new TaskFragmentAdapter(getSupportFragmentManager());
//        viewPager.setAdapter(mFragmentAdapter);
//        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
//            @Override
//            public void onPageSelected(int position) {
//                hideAllButton();
//                if (position == 0) {
//                    tvSignInTask.setSelected(true);
//                }
//                if (position == 1) {
//                    tvDailyTask.setSelected(true);
//                }
//                if (position == 2) {
//                    tvBindingTask.setSelected(true);
//                }
//            }
//        });
//        tvSignInTask.setOnClickListener(v -> viewPager.setCurrentItem(0));
//        tvDailyTask.setOnClickListener(v -> viewPager.setCurrentItem(1));
//        tvBindingTask.setOnClickListener(v -> viewPager.setCurrentItem(2));
//        viewPager.setCurrentItem(0);
//        tvSignInTask.setSelected(true);
//
//        final List<Fragment> fragments = new ArrayList<>();
//        //签到任务
//        mSignInTaskFragment = SignInTaskFragment.newInstance();
//        //绑定任务
//        mTaskFragment = BindingTaskFragment.newInstance();
//        //日常任务
//        mDailyTaskFragment = DailyTaskFragment.newInstance();
//        fragments.add(mSignInTaskFragment);
//        fragments.add(mTaskFragment);
//        fragments.add(mDailyTaskFragment);
//        mFragmentAdapter.setFragments(fragments);
    }


//    private void hideAllButton() {
//        tvSignInTask.setSelected(false);
//        tvDailyTask.setSelected(false);
//        tvBindingTask.setSelected(false);
//    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void retryRefreshData() {

    }

    @Override
    public void showContent() {
        viewPagerCard.setVisibility(View.VISIBLE);
        cardView.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
        netErrorContainer.setVisibility(View.GONE);
    }

    @Override
    public void showProgress() {
        progressBar.setVisibility(View.VISIBLE);
        viewPagerCard.setVisibility(View.GONE);
        cardView.setVisibility(View.GONE);
        netErrorContainer.setVisibility(View.GONE);
    }

    @Override
    public void showError(Throwable throwable) {
        progressBar.setVisibility(View.GONE);
        if (throwable instanceof UnknownHostException
                || throwable instanceof UnknownServiceException
                || throwable instanceof TimeoutException || throwable instanceof ConnectException) {
            showNetErrorView();
        } else {
            LogUtil.e(TAG, "throwable is not instanceof 4 Exception");
        }
    }

    private void showNetErrorView() {
        netErrorContainer.setVisibility(View.VISIBLE);
        cardView.setVisibility(View.GONE);
        viewPagerCard.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showEmpty() {

    }

    @OnClick(R.id.net_error_container)
    public void retry() {
        mPresenter.loadSignInfo();
    }

    @Override
    public void initData() {
        mPresenter.loadSignInfo();
        //打开签到页面时直接签到
        int signStatus = getIntent().getIntExtra(SIGN_STATUS, 0);
        if (signStatus == 0) {
            mPresenter.signIn(0);
        }
    }

    @Override
    public void showData(SignInInfo data) {
        mWeekAdapter.setData(data.getUserWeekSign());
        mWeekAdapter.setData(data);
        tvContinuousCheckIn.setText("已连续签到" + data.getUserSignedCount() + "天");

        SignInRuleAdapter adapter = new SignInRuleAdapter(data.getUserSignTask(), data.getSignInRule());
        adapter.setInteractionListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void UpdateSignInfo() {

    }

    /**
     * 签到成功的回调
     *
     * @param signIn
     */
    @Override
    public void onSignInSucceed(SignIn signIn) {
        SignInDialog dialog = new SignInDialog();
        dialog.setSignInfo(signIn);
        dialog.show(getSupportFragmentManager(), "");

        //通知上一页已经签到完成
        setResult(RESULT_OK);
    }

    /**
     * 签到失败的回调
     *
     * @param throwable 签到失败的异常
     */
    @Override
    public void onSignInFailed(Throwable throwable) {
        if (throwable != null)
            ToastUtil.makeShortToast(throwable.getMessage());
    }


    /**
     * 领取任务后调用
     */
    @Override
    public void setReceivingCompleted() {
        mPresenter.loadSignInfo();
    }

    /**
     * 用户点击签到的时候调用
     *
     * @param weekday
     */
    @Override
    public void OnSignInClicked(int weekday) {
        mPresenter.signIn(weekday);
    }

    /**
     * 显示分享对话框
     *
     * @param weekday
     */
    @Override
    public void showShareDialog(int weekday) {
        mShareDialog = SupplementDialog.newInstance(weekday, SupplementDialog.SHARE);
        mShareDialog.setInteractionListener(this);
        mShareDialog.show(getSupportFragmentManager(), "share");
    }

    /**
     * 显示充值对话框
     *
     * @param weekday
     */
    @Override
    public void showRechargeDialog(int weekday) {
        mRechargeDialog = SupplementDialog.newInstance(weekday, SupplementDialog.RECHARGE);
        mRechargeDialog.setInteractionListener(this);
        mRechargeDialog.show(getSupportFragmentManager(), "recharge");
    }

    /**
     * 充值按钮点击后回调
     *
     * @param weekDay
     */
    @Override
    public void onRechargeClicked(int weekDay) {
        if (mRechargeDialog != null && mRechargeDialog.isAdded()) {
            mRechargeDialog.dismiss();
        }
        mWeekDay = weekDay;
        Intent intent = new Intent(this, PayCenterActivity.class);
        startActivityForResult(intent, 1);
    }

    private int mWeekDay;

    /**
     * 分享按钮点击后回调
     */
    @Override
    public void onShareClicked(int weekDay) {
        if (mShareDialog != null && mShareDialog.isAdded()) {
            mShareDialog.dismiss();
        }
        mWeekDay = weekDay;
        UMWeb web = new UMWeb("https://www.resouxs.com/app/download/");
        web.setTitle("热搜小说阅读器");
        web.setDescription("我正在用热搜小说APP，喜欢的书任意看，还有更多免费书籍！——跟我一起来看书吧!");
        new ShareAction(this)
                .withMedia(web)
                .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE)
                .setCallback(umShareListener).open();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        //充值成功的判断方法
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                mPresenter.signIn(mWeekDay);
            }
        }
    }

    boolean shared;

    @Override
    protected void onStart() {
        super.onStart();
        if (shared) {
            mPresenter.signIn(mWeekDay);
            shared = false;
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            switch (platform) {
                case WEIXIN:
                case WEIXIN_CIRCLE:
                    if (!WXUtils.isWeixinAvilible(SignInActivity.this)) {
                        ToastUtil.makeShortToast("您未安装微信，请选择其他分享方式");
                        return;
                    }
                    break;
                case QZONE:
                case QQ:
                    if (!WXUtils.isQQClientAvailable(SignInActivity.this)) {
                        ToastUtil.makeShortToast("您未安装QQ，请选择其他分享方式");
                        return;
                    }
                    break;
            }
            shared = true;
//            new Handler().postDelayed(() -> , 1000);
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
        }
    };

    private void openAppMarket(String packageName) {
        try {
            String str = "market://details?id=" + packageName;
            Intent localIntent = new Intent(Intent.ACTION_VIEW);
            localIntent.setData(Uri.parse(str));
            startActivity(localIntent);
        } catch (Exception e) {
            // 打开应用市场失败 可能是没有手机没有安装应用市场
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "打开应用市场失败", Toast.LENGTH_SHORT).show();
            // 调用系统浏览器进入市场
            String url = packageName;
            openLinkBySystem(url);
        }
    }

    /**
     * 调用系统浏览器打开网页
     *
     * @param url 地址
     */
    private void openLinkBySystem(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    /**
     * 去完成
     */
    @Override
    public void onToCompleteClicked() {

    }

    /**
     * 领取任务
     *
     * @param taskId
     */
    @Override
    public void onReceiveClicked(String taskId) {
        mPresenter.receiveWelfare(taskId);
    }
}
